{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9484ec32-54a6-4e8d-b0bd-fcba9562440c",
   "metadata": {},
   "source": [
    "Chapter 22\n",
    "# 利用groupby() 汇总学生成绩\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0bf49e2b-dabb-4b7e-a2ed-3633bc5ac74c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "acbdc3d9-b4b4-4f8e-a5da-c707167b5c9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建班级、学号和科目的所有可能组合\n",
    "classes = ['A', 'B']\n",
    "stu_ids = [1, 2, 3, 4]\n",
    "subjects = ['Art', 'Math', 'Science']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a7e0947c-35b7-4c0b-b464-95abc0ed53c9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 使用随机数生成成绩数据\n",
    "np.random.seed(0)\n",
    "length = len(classes ) * len(stu_ids) * len(subjects)\n",
    "data = np.random.randint(3, 6, size=(length))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "39b68e18-32fa-487a-ac4a-713677930c70",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>Score</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Class</th>\n",
       "      <th>Student ID</th>\n",
       "      <th>Subject</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"12\" valign=\"top\">A</th>\n",
       "      <th rowspan=\"3\" valign=\"top\">1</th>\n",
       "      <th>Art</th>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Math</th>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Science</th>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"3\" valign=\"top\">2</th>\n",
       "      <th>Art</th>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Math</th>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Science</th>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"3\" valign=\"top\">3</th>\n",
       "      <th>Art</th>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Math</th>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Science</th>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"3\" valign=\"top\">4</th>\n",
       "      <th>Art</th>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Math</th>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Science</th>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"12\" valign=\"top\">B</th>\n",
       "      <th rowspan=\"3\" valign=\"top\">1</th>\n",
       "      <th>Art</th>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Math</th>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Science</th>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"3\" valign=\"top\">2</th>\n",
       "      <th>Art</th>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Math</th>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Science</th>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"3\" valign=\"top\">3</th>\n",
       "      <th>Art</th>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Math</th>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Science</th>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"3\" valign=\"top\">4</th>\n",
       "      <th>Art</th>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Math</th>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Science</th>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                          Score\n",
       "Class Student ID Subject       \n",
       "A     1          Art          3\n",
       "                 Math         4\n",
       "                 Science      3\n",
       "      2          Art          4\n",
       "                 Math         4\n",
       "                 Science      5\n",
       "      3          Art          3\n",
       "                 Math         5\n",
       "                 Science      3\n",
       "      4          Art          3\n",
       "                 Math         3\n",
       "                 Science      5\n",
       "B     1          Art          4\n",
       "                 Math         5\n",
       "                 Science      5\n",
       "      2          Art          3\n",
       "                 Math         4\n",
       "                 Science      4\n",
       "      3          Art          4\n",
       "                 Math         4\n",
       "                 Science      3\n",
       "      4          Art          4\n",
       "                 Math         3\n",
       "                 Science      3"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 创建多行标签数据帧\n",
    "index = pd.MultiIndex.from_product(\n",
    "    [classes, stu_ids, subjects], \n",
    "    names=['Class', 'Student ID', 'Subject'])\n",
    "df = pd.DataFrame(data, index=index, columns=['Score'])\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a97d219f-d4d8-4455-a5b0-31062dccc4fa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Class  Subject\n",
       "A      Art        3.25\n",
       "       Math       4.00\n",
       "       Science    4.00\n",
       "B      Art        3.75\n",
       "       Math       4.00\n",
       "       Science    3.75\n",
       "Name: Score, dtype: float64"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1) 每个班级各个科目平均成绩\n",
    "class_subject_avg = df.groupby(\n",
    "    ['Class', 'Subject'])['Score'].mean()\n",
    "class_subject_avg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "cc58482c-235a-4b78-9d4c-3cd15f3991cc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Class  Student ID\n",
       "A      1             3.333333\n",
       "       2             4.333333\n",
       "       3             3.666667\n",
       "       4             3.666667\n",
       "B      1             4.666667\n",
       "       2             3.666667\n",
       "       3             3.666667\n",
       "       4             3.333333\n",
       "Name: Score, dtype: float64"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2) 每个班级各个学生的平均成绩\n",
    "class_student_avg = df.groupby(\n",
    "    ['Class', 'Student ID'])['Score'].mean()\n",
    "class_student_avg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a1d7cac3-6fde-4519-a4e6-9a3db3df6eeb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Subject\n",
       "Art        3.500\n",
       "Math       4.000\n",
       "Science    3.875\n",
       "Name: Score, dtype: float64"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 3) 两个班级放在一起各个科目平均成绩\n",
    "both_class_avg = df.groupby(\n",
    "    'Subject')['Score'].mean()\n",
    "both_class_avg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a85f7c0b-759f-4e21-a424-25aa406de966",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Class  Student ID\n",
       "B      1             14\n",
       "A      2             13\n",
       "       3             11\n",
       "       4             11\n",
       "B      2             11\n",
       "       3             11\n",
       "A      1             10\n",
       "B      4             10\n",
       "Name: Score, dtype: int32"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 4) 两个班级每个同学总成绩，并排名\n",
    "student_total_score = df.groupby(\n",
    "    ['Class','Student ID'])['Score'].sum().sort_values(\n",
    "    ascending=False)   \n",
    "student_total_score"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
